using System;
using System.Collections.Generic;
using System.Text;
using Tomahawk.Runtime.Debug.Exceptions;
using System.Xml.Serialization;

namespace Tomahawk.Runtime.Logic
{
    /// <summary>
    /// Logic Base Object. 
    /// This class provides the logic objects with all the required common functionalities for logic objects.
    /// </summary>
    public abstract class XObject
    {
        /// <summary>
        /// Constructor
        /// </summary>
        public XObject()
        {
            this.started = false;
            this.pendantObjects = new List<XObject>();
#if DEBUG
            _objSerialNumber = _objSerialNCounter;
            _objSerialNCounter++;
            //DEBUG: uncomment for object trazability
            //if (_objSerialNumber == 15) _objSerialNumber = _objSerialNumber;
#endif
        }

        #region "Id"

        private string name = "";

        public string Name
        {
            get { return name; }
        }

        internal void SetName(string objName)
        {
            name = objName;
        }

#if DEBUG
        //
        // object trazability for debuging pourposese
        //
        private static int _objSerialNCounter = 0;
        private int _objSerialNumber;
        public int SerialNumber
        {
            get { return _objSerialNumber; }
        }
#endif

        #endregion

        #region "Update Logic"

        private bool updateRequired;

        /// <summary>
        /// This property indicates this logic entity requires to be updated each frame
        /// </summary>
        public bool UpdateRequired
        {
            get { return updateRequired; }
            set { updateRequired = value; }
        }

        protected bool preBeginPlayExecuted = false;

        protected bool postBeginPlayExecuted = false;

        private bool started = false;
        
        [XmlIgnore()]
        public bool Started { get { return started; } }

        /// <summary>
        /// This will update the entity
        /// </summary>
        internal void Update(float elapsedTime)
        {
            //if it's the first time we call an Update on the object
            if (this.initialized)
            {
                //call pre begin play on first on first updat try
                if (!this.started)
                {
                    //execute pre begin play on the object
                    if (!this.preBeginPlayExecuted)
                    {
                        this.OnPreBeginPlay();
                        this.preBeginPlayExecuted = true;
                    }

                    //if postbeginplay is already executed in all children
                    //execute in this object, and then start updating normally
                    if (this.preBeginPlayExecuted && !this.postBeginPlayExecuted)
                    {
                        if (XWorld.Instance.AllChildrenStarted(this))
                        {
                            this.OnPostBeginPlay();
                            this.postBeginPlayExecuted = true;
                        }
                    }
                }

                //call update on this logic node
                if (this.preBeginPlayExecuted && this.postBeginPlayExecuted)
                {
                    this.started = true;
                    if (this.updateRequired) this.OnUpdate(elapsedTime);
                }
            }

        }

        #endregion

        #region "Pause Management"

        private bool pausableObject = true;

        private bool paused = false;

        /// <summary>
        /// Allow flag derived objects as pausables
        /// </summary>
        protected bool PausableObject
        {
            set { this.pausableObject = value; }
        }

        /// <summary>
        /// Indicates if the object is pausable
        /// </summary>
        public bool IsPausableObject
        {
            get { return this.pausableObject; }
        }

        /// <summary>
        /// Get/sets the paused state. 
        /// Only pausable objects can get this property set to true.
        /// </summary>
        internal bool Paused
        {
            get { return this.paused; }
            set
            {
                if (this.pausableObject)
                {
                    if (this.paused != value)
                    {
                        this.paused = value;
                        if (this.paused) this.OnPause();
                        else this.OnResume();
                    }
                }
                else
                {
                    //if the object is not pausable, give a warning to the user
                    Engine.Instance.DebugConsole.Warn(
                        string.Format("Object '{0}' of type '{1}' is not pausable!", this.name, this.GetType()));
                    this.paused = false;
                }
            }
        }

        /// <summary>
        /// Override this to provide custom pause logic
        /// </summary>
        protected virtual void OnPause()
        { }

        /// <summary>
        /// Override this to provide custom resume logic
        /// </summary>
        protected virtual void OnResume()
        { }

        #endregion

        #region "Initialization"

        private bool initialized = false;

        private bool autoInit = true;

        /// <summary>
        /// Gets / Sets if the object must be autoinitialized
        /// </summary>
        internal bool AutoInit
        {
            get { return this.autoInit; }
            set { this.autoInit = value; }
        }

        /// <summary>
        /// Indicate if the object had been already initialized
        /// </summary>
        public bool Initialized
        {
            get { return initialized; }
        }

        /// <summary>
        /// Object initialization
        /// </summary>
        public void Initialize()
        {
            //initialize only once
            if (!initialized)
            {
                this.initialized = true;

                //let the derived code register their children
                this.OnRegisterChildren();

                //Let the derived code initialize
                this.OnInitialize();

                //Initialize our pendant objects
                this.initializePendantObjects();

                //Notify all children initialized
                this.OnAfterInitialize();
            }
        }

       
        #endregion

        #region "Readyness"

        /// <summary>
        /// Flag that indicates if all the object resource are ready
        /// </summary>
        private bool isReady = false;

        /// <summary>
        /// Returns true when all the resources for this object are loaded and ready
        /// </summary>
        public bool IsReady
        {
            get
            {
                //if the object was not yet ready, check again if all resources are loaded
                if (!isReady) isReady = this.checkResourcesReady();
                return this.isReady;
            }
        }

        /// <summary>
        /// Override this to provide when all the resources for this object are ready
        /// </summary>
        protected virtual bool checkResourcesReady()
        {
            return true;
        }

        #endregion

        #region "Overridable Events"

        /// <summary>
        /// Override this to provide the update logic of the node
        /// </summary>
        protected virtual void OnUpdate(float elapsedTime)
        {
        }

        protected virtual void OnPreBeginPlay()
        {
        }

        protected virtual void OnPostBeginPlay()
        {
        }

        protected virtual void OnInitialize()
        {
        }

        protected virtual void OnRegisterChildren()
        {
        }

        protected virtual void OnAfterInitialize()
        {
        }

        #endregion

        #region "Parentship"

        protected XObject parent;

        /// <summary>
        /// Set the parent object
        /// </summary>
        internal void SetParent(XObject parentObj)
        {
            parent = parentObj;
        }

        /// <summary>
        /// Register this object as a children.
        /// Use this method to register objects automatically instanced via archetype.
        /// This will privent object from autoinitialize, so you'll have to manually initialyze them.
        /// </summary>
        public void RegisterAsChildren(XObject obj)
        {
            //Register object in the world
            XWorld.Instance.registerObject(this, "", obj);
            
            //Register as pendant of this object
            pendantObjects.Add(obj);
        }

        /// <summary>
        /// Parent object
        /// </summary>
        public XObject Parent
        {
            get { return parent; }
        }

        /// <summary>
        /// List of objects registered as Children of this one
        /// </summary>
        private List<XObject> pendantObjects;

        /// <summary>
        /// Initializes all the pendant objects
        /// (only those that are autoinit)
        /// </summary>
        private void initializePendantObjects()
        {
            foreach (XObject obj in this.pendantObjects)
            {
                if (obj.autoInit) obj.Initialize();
            }
            this.pendantObjects.Clear();
        }

        #endregion

        #region "Destruction flag"

        private bool markedForDestruction = false;

        public bool MarkedForDestruction
        {
            get { return markedForDestruction; }
        }

        internal void MarkForDestruction()
        {
            markedForDestruction = true;
        }

        /// <summary>
        /// Utility method to invoke destruction directly on an XObject.
        /// It simply calls XWorld implementation of destruction.
        /// </summary>
        public void Destroy()
        {
            XWorld.Instance.DeferedDestroyObject(this);
        }

        public virtual void OnBeforeDestroy() { }

        public virtual void OnAfterDestroy() { }

        #endregion

        #region "Exceptions"

        /// <summary>
        /// Base exception for all errors that are expected to occur in the logic layer
        /// </summary>
        public class LogicException : Debug.Exceptions.XEngineException
        {
            public LogicException(string msg, Exception inner) : base(ExceptionSeverity.Warning, msg, inner) { }
        }

        #endregion
    }

}
